import { message, Skeleton, Tooltip } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

import reportService from '@/api/services/reportService';
// import { useThemeToken } from '@/theme/hooks';

import userService from '@/api/services/userService';

import 'dayjs/locale/zh-cn';

import { wordFreqItem, statisticsListItem, userListItem, topquestions } from '@/common/types';

// import Back from '@/components/router/Back';
// import { useParams } from '@/router/hooks';
// import RouterMenu from '../components/menus/RouterMenu';
// import LineChart from './components/LineChart';
// import styles from './styles/Report.module.css';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';

// import { boardDate } from '@/utils/report';
import TipDesc from '@/components/tipDesc/tipDesc';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useManagePage } from '@/store/configStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';

import MobileReportHeader from './components/MobileReportHeader';
import ReportHeader from './components/ReportHeader';
import SmoothLineChart from './components/SmoothLineChart';
import UserBarChart from './components/UserBarChart';
import UserTable from './components/UserTableV2';
import ReportContextProvider from './context';
import './styles/styles.css';

dayjs.locale('zh-cn');

interface ReportProps {
  renderTitle: any;
}

const tooltipMap: Record<string, string> = {
  userTotal: '累计使用过该应用的用户总量（去重统计），反映用户覆盖范围。',
  sessionCount: '累计使用过该应用的用户总量（去重统计），反映用户覆盖范围。',
  questionCount: '累计产生的对话总条数（单轮问答计一条），体现用户与应用的交互总量。',
  total: '当前时间范围内使用该应用的用户总数，包含新增用户与重复用户',
  new: '首次使用该应用的用户数量，不包含重复使用的老用户。',
  overlap: '曾使用过该应用并在当前时间范围内再次活跃的用户数量。',
  session: '当前时间范围内，用户在应用中发起的连续问答交互过程，每段多轮对话计为一次会话。',
  question: '当前时间范围内，用户与应用之间的单轮问答总条数，每次提问和回答计为一条对话。',
  TTFB: '用户提问后，应用作出首个回复的平均耗时，数值越小代表响应越快，反映应用的服务即时性。',
};

function Report({ renderTitle: _renderTitle }: ReportProps) {
  // const router = useRouter();
  const [, contextHolder] = message.useMessage();
  // const modal = useModal('dialogue');
  // const { id } = useParams();

  // const [id, setId] = useState("");
  // useEffect(() => {
  //   const searchParams = new URLSearchParams(location.search);
  //   const id = searchParams.get('appId') || '67fcd7c1de9ddb56bea37b6c'
  //   setId(id)
  // }, []);

  const searchParams = new URLSearchParams(location.search);
  const id = searchParams.get('appId');

  const { isPc: isPcDisplay } = useWindowWidth();
  const {
    isInOrchestrationPage,
    userTrendsList,
    setUserTrendsList,
    userTrendsChartData,
    setUserTrendsChartData,
    dialogueList,
    setDialogueList,
    dialogueChartData,
    setDialogueChartData,
  } = useOrchestrationStore();
  const isPc = isInOrchestrationPage || isPcDisplay;

  // const { colorBgBase, colorPrimary } = useThemeToken();

  const [wordCloudData, setWordCloudData] = useState<wordFreqItem[]>([]);
  const [chartData, setChartData] = useState<statisticsListItem[]>([]);
  const [topQuestions, setTopQuestions] = useState<topquestions[]>([]);
  const [users, setUsers] = useState<userListItem[]>([]);
  const [userCount, setUserCount] = useState(0);

  const [totalUsers, setTotalUsers] = useState(0);
  const [totalQuestions, setTotalQuestions] = useState(0);
  const [totalConversation, setTotalConversation] = useState(0);
  const [totalSatisfaction, setTotalSatisfaction] = useState(100);

  const [userLoading, setUserLoading] = useState(false);
  const [wordFreqLoading, setWordFreqLoading] = useState(false);
  const [statisticsAllLoading, setStatisticsAllLoading] = useState(false);
  const [statisticsLoading, setStatisticsLoading] = useState(false);
  const managePage = useManagePage();
  const [showCount, setShowCount] = useState({
    userCount: 0,
    sessionCount: 0,
    questionCount: 0,
  });
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(6, 'day'),
    dayjs(),
  ]);
  const [activeRange, setActiveRange] = useState('7days');

  const [roles, setRoles] = useState([{ code: '', name: '全局统计' }]);
  const [selectedRole, setSelectedRole] = useState('');

  const [isShowDialog, setIsShowDialog] = useState(true);
  const fetchData = async (id: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const response = await reportService.statisticsList(
        id,
        {
          start: startDate,
          end: endDate,
        },
        selectedRole,
      );
      response.forEach((item) => {
        // 处理边界情况
        if (item.questionCount <= 0) {
          item.satisfaction = '100'; // 默认值
          return;
        }

        // 计算原始值并确保在[0, 100]范围内
        const rawValue = (1 - item.unLikeCount / item.questionCount) * 100;
        const clampedValue = Math.max(0, Math.min(100, rawValue));

        item.satisfaction = clampedValue.toFixed(2);
      });
      console.log('fetchData', response);
      setChartData(response);
    } catch (error) {
    } finally {
      setStatisticsLoading(false);
    }
  };

  const fetchAppUserList = async (id: string) => {
    // try {
    //   setUserLoading(true);
    //   const { data, count } = await reportService.appUserList(id, selectedRole);
    //   // const response = await reportService.appUserList(id);
    //   data.forEach((item) => {
    //     item.questions = [];
    //   });
    //   // data.sort((a, b) => b.usageDays - a.usageDays);
    //   // data.sort((a, b) => b?.questionCount - a?.questionCount);
    //   console.log('fetchAppUserList', data);
    //   setUsers(data);
    //   setUserCount(count);
    // } catch (error) {
    // } finally {
    //   setUserLoading(false);
    // }
  };

  const fetchwordFreq = async (id: string) => {
    try {
      setWordFreqLoading(true);
      const response = await reportService.wordFreq(id, selectedRole);
      console.log('wordFreq', response);
      setWordCloudData(response?.wordFreq || []);
    } catch (error) {
    } finally {
      setWordFreqLoading(false);
    }
  };

  const statisticsAll = async (id: string) => {
    try {
      setStatisticsAllLoading(true);
      const response = await reportService.statisticsAll(id, selectedRole);
      console.log('statisticsAll', response);
      setTotalUsers(response?.userCount ?? 0);
      setTotalQuestions(response?.questionCount ?? 0);
      setTotalConversation(response?.total ?? 0);
      setTotalSatisfaction(
        response?.questionCount ? 100 * (1 - response?.unLikeCount / response?.questionCount) : 0,
      );
    } catch (error) {
    } finally {
      setStatisticsAllLoading(false);
    }
  };

  const getConversationCount = () => {};

  const getRoles = () => {
    userService
      .getRoles()
      .then((response) => {
        console.log(response?.roles);
        const updatedRoles = [{ code: '', name: '全局统计' }, ...response?.roles];
        setRoles(updatedRoles);
      })
      .catch((error) => {
        console.error('Failed to fetch roles:', error);
      });
  };

  const handleRoleChange = (value: string) => {
    setSelectedRole(value);
  };

  useEffect(() => {
    if (id) {
      fetchData(id, dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD'));
      handleTrends(id, dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD'));
      handleTop(id, dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD'));
      getCountData(id);
    }
  }, [id, dateRange, selectedRole]);

  useEffect(() => {
    if (id) {
      handleDialogue(
        id,
        dateRange[0].format('YYYY-MM-DD'),
        dateRange[1].format('YYYY-MM-DD'),
        isShowDialog ? 'chatDigital' : 'ttfbDigital',
      );
    }
  }, [id, dateRange, selectedRole, isShowDialog]);

  useEffect(() => {
    if (id) {
      fetchAppUserList(id);
      fetchwordFreq(id);
      statisticsAll(id);
      // getRoles();
    }
  }, [id, selectedRole]);

  const handleDateChange = (dates: [dayjs.Dayjs, dayjs.Dayjs]) => {
    if (dates && dates.length === 2) {
      const [start, end] = dates;
      const diffDays = end.diff(start, 'day');

      // 如果日期范围超过30天，自动调整为结束日期的前30天
      if (diffDays > 29) {
        const adjustedStart = end.subtract(29, 'day');
        setDateRange([adjustedStart, end]);
        message.info('超出30天，按照近30天展示');
      } else {
        setDateRange([start, end]);
      }
      if (diffDays != 29 && diffDays != 6) {
        setActiveRange('days');
      }
    }
  };
  const [visible, setVisible] = useState(false);

  // const handleIconClick = () => {
  //   setVisible(true); // 点击图标时显示日期选择器
  // };

  // 处理快捷选项点击
  // const handleQuickSelect = (days: any, activeRange: string = '') => {
  //   const endDate = dayjs().endOf('day');
  //   const startDate = dayjs().subtract(days, 'days').startOf('day');
  //   setDateRange([startDate, endDate]);
  //   setActiveRange(activeRange);
  // };
  const handleQuickSelect = (days: number, activeRange = '') => {
    const endDate = dayjs().startOf('day');
    const startDate = endDate.subtract(days - 1, 'days').startOf('day');
    setDateRange([startDate, endDate]);
    setActiveRange(activeRange);
  };
  // 用户
  const handleTrends = async (id: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const res = await reportService.statisticsTrends(id, {
        startTime: startDate,
        endTime: endDate,
      });
      setUserTrendsList(res.statistics);
      setUserTrendsChartData(res.chart);
    } catch (error) {
    } finally {
      setStatisticsLoading(false);
    }
  };
  // 对话
  const handleDialogue = async (
    id: string,
    startDate: string,
    endDate: string,
    urlText: string,
  ) => {
    try {
      const res = await reportService.statisticsDialogue(
        id,
        {
          startTime: startDate,
          endTime: endDate,
        },
        urlText,
      );
      setDialogueList(res.statistics);
      setDialogueChartData(res.chart);
    } catch (error) {
      message.error(error);
    }
  };
  // top10
  const handleTop = async (id: string, startDate: string, endDate: string) => {
    try {
      setStatisticsLoading(true);
      const res = await reportService.statisticsTop(id, {
        startTime: startDate,
        endTime: endDate,
      });
      setTopQuestions(res.data);
    } catch (error) {
    } finally {
      setStatisticsLoading(false);
    }
  };
  const getCountData = async (id: string) => {
    try {
      const res = await reportService.getStatisticsData(id);
      setShowCount(res);
    } catch (error) {
      console.log(error);
    }
  };

  // 计算出昵称
  const handleTrendsChange = (key: string) => {
    return key == 'total'
      ? '总用户'
      : key == 'new'
      ? '新增用户'
      : key == 'overlap'
      ? '重叠用户'
      : key == 'session'
      ? '会话数'
      : key == 'TTFB'
      ? '首字延时'
      : '对话数';
  };

  return (
    <div className={`flex h-full flex-col ${isPc ? '' : ''}`}>
      {contextHolder}
      {isPc ? (
        <ReportHeader
          handleDateChange={handleDateChange}
          handleQuickSelect={handleQuickSelect}
          dateRange={dateRange}
          showCount={showCount}
          activeRange={activeRange}
          tooltipMap={tooltipMap}
        />
      ) : (
        <MobileReportHeader
          handleDateChange={handleDateChange}
          handleQuickSelect={handleQuickSelect}
          dateRange={dateRange}
          activeRange={activeRange}
        />
      )}

      {isPc ? (
        <div className=" mb-2 flex gap-4 overflow-x-auto" style={{ height: '46vh' }}>
          <div
            className="hide-scrollbar min-w-[500px] flex-1 overflow-auto rounded-default py-2 "
            style={{ backgroundColor: '#fff', position: 'relative', zIndex: 1 }}
          >
            <div className="px-4">
              <div className=" flex h-[40px] items-center text-xl font-semibold ">
                <div className="mr-2 h-3 w-3  rounded-full border-[3px] border-[#1B6DFA]" />
                用户趋势
              </div>
              <TipDesc
                title="展示平台用户数量随时间的变化趋势，帮助分析用户活跃度和增长情况"
                className="!my-0"
              />
              <div className="mt-2 flex items-center justify-between gap-4">
                {userTrendsList.map((item: any, index: number) => {
                  return (
                    <div
                      key={index}
                      className="   flex h-[108px]  w-1/3  rounded-md bg-[#F7F8FA] p-4 text-text-4"
                    >
                      <div className="mr-3 flex h-11 w-11 items-center justify-center rounded-md bg-white">
                        <SvgIcon
                          size={24}
                          icon={
                            item.key == 'total'
                              ? 'reportline1'
                              : item.key == 'new'
                              ? 'reportline2'
                              : 'reportline3'
                          }
                        />
                      </div>
                      <div>
                        <div className="flex items-center text-text-4">
                          {handleTrendsChange(item.key)}
                          <Tooltip title={tooltipMap[item.key]}>
                            <div className="flex">
                              <SvgIcon size={16} icon="report-is1" className="ml-1" />
                            </div>
                          </Tooltip>
                        </div>
                        <div className="mb-1">
                          <span className="mr-1 text-2xl font-extrabold text-text-5">
                            {userTrendsChartData.length > 0 ? item.count : '-'}
                          </span>
                          人
                        </div>
                        <div className="flex items-center">
                          {userTrendsChartData.length > 0 && (
                            <>
                              <span className=" text-sm text-text-4">
                                {activeRange === '7days'
                                  ? ' 周'
                                  : activeRange === '30days'
                                  ? '月'
                                  : ''}
                                环比
                                <span
                                  className={`${
                                    item.comparison == '-'
                                      ? 'text-text-4'
                                      : item.comparison == 0
                                      ? 'text-[#1E6FF8]'
                                      : item.comparison > 0
                                      ? 'text-[#0AA664]'
                                      : 'text-error'
                                  }
                                      px-1
                                      `}
                                >
                                  {item.comparison > 0 ? '+' : ''}
                                  {item.comparison == '-'
                                    ? '-'
                                    : (() => {
                                        const percent = (item.comparison * 100).toFixed(2);
                                        return percent.endsWith('.00')
                                          ? `${parseInt(percent, 10)}%`
                                          : `${percent}%`;
                                      })()}
                                </span>
                              </span>
                              {item.comparison !== 0 && item.comparison !== '-' ? (
                                <SvgIcon
                                  size={16}
                                  icon={item.comparison > 0 ? 'report-is-top ' : 'report-is-bottom'}
                                />
                              ) : (
                                <div className="text-[#1E6FF8]">-</div>
                              )}
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            <div className="mt-2">
              {statisticsLoading ? (
                <Skeleton active paragraph={{ rows: 5 }} style={{ padding: '10px' }} />
              ) : (
                <div className="h-[220px]">
                  {userTrendsChartData.length > 0 ? (
                    <UserBarChart data={userTrendsChartData} height={210} />
                  ) : (
                    <div className="h-full">
                      <NotData />
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
          <div
            className="hide-scrollbar min-w-[500px] flex-1 overflow-auto rounded-default bg-white py-2 "
            style={{ height: '100%', position: 'relative', zIndex: 1 }}
          >
            <div className="px-4">
              <div className="flex h-[40px] items-center justify-between">
                <div className="flex items-center text-xl font-semibold ">
                  <div className="mr-2 h-3 w-3  rounded-full border-[3px] border-[#1B6DFA]" />
                  <div className="flex cursor-pointer items-center">
                    <span className={` mr-4`}>{isShowDialog ? '对话趋势' : '性能趋势'}</span>
                  </div>
                </div>
                <div className="flex h-8 w-[168px] cursor-pointer items-center justify-center rounded-md border border-line-2 p-1 text-text-4 ">
                  <div
                    className={`${
                      isShowDialog ? 'rounded bg-fill-1 font-semibold text-[#1E6FFA]' : ' '
                    } w-1/2 text-center `}
                    onClick={() => {
                      setIsShowDialog(true);
                    }}
                  >
                    对话趋势
                  </div>
                  <div
                    className={`${
                      isShowDialog ? '' : 'rounded bg-fill-1 font-semibold text-[#1E6FFA]'
                    } w-1/2 text-center `}
                    onClick={() => {
                      setIsShowDialog(false);
                    }}
                  >
                    性能趋势
                  </div>
                </div>
              </div>
              <TipDesc
                title={
                  isShowDialog
                    ? '统计和展示用户与系统的对话数量及变化趋势'
                    : '展示系统首字时延的变化趋势，反映系统响应速度和性能表现'
                }
                className="!my-0"
              />
              <div className="mt-2 flex items-center justify-between gap-4">
                {dialogueList.map((item: any, index: number) => {
                  return (
                    <div
                      key={index}
                      className={` flex h-[108px]  ${
                        isShowDialog ? 'w-1/2' : 'w-full'
                      } rounded-md  bg-[#F7F8FA]  p-4 text-text-4 `}
                    >
                      <div className="mr-3 flex h-11 w-11 items-center justify-center rounded-md bg-white">
                        <SvgIcon
                          size={24}
                          icon={
                            item.key == 'session'
                              ? 'reportline4'
                              : item.key == 'TTFB'
                              ? 'reportline6'
                              : 'reportline5'
                          }
                        />
                      </div>
                      <div>
                        <div className="flex items-center">
                          {handleTrendsChange(item.key)}
                          <Tooltip title={tooltipMap[item.key]}>
                            <div className="flex">
                              <SvgIcon size={16} icon="report-is1" className="ml-1" />
                            </div>
                          </Tooltip>
                        </div>
                        <div className="mb-1">
                          <span className="mr-1 text-2xl font-extrabold text-text-5">
                            {dialogueChartData.length > 0 ? item.count : '-'}
                          </span>
                          {item.key == 'session' ? '个' : item.key == 'TTFB' ? '秒' : '条'}
                        </div>
                        <div className="flex items-center">
                          {dialogueChartData.length > 0 && (
                            <>
                              <span className=" text-sm text-text-4">
                                {activeRange === '7days'
                                  ? ' 周'
                                  : activeRange === '30days'
                                  ? '月'
                                  : ''}
                                环比
                                <span
                                  className={`${
                                    item.comparison == '-'
                                      ? 'text-text-4'
                                      : item.comparison == 0
                                      ? 'text-[#1E6FF8]'
                                      : item.comparison > 0
                                      ? 'text-[#0AA664]'
                                      : 'text-error'
                                  }
                                  px-1
                                  `}
                                >
                                  {item.comparison > 0 ? '+' : ''}
                                  {item.comparison == '-'
                                    ? '-'
                                    : (() => {
                                        const percent = (item.comparison * 100).toFixed(2);
                                        return percent.endsWith('.00')
                                          ? `${parseInt(percent, 10)}%`
                                          : `${percent}%`;
                                      })()}
                                </span>
                              </span>
                              {item.comparison !== 0 && item.comparison !== '-' ? (
                                <SvgIcon
                                  size={16}
                                  icon={item.comparison > 0 ? 'report-is-top ' : 'report-is-bottom'}
                                />
                              ) : (
                                <div className="text-[#1E6FF8]">-</div>
                              )}
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            <div className="mt-2">
              {statisticsLoading ? (
                <Skeleton active paragraph={{ rows: 5 }} style={{ padding: '10px' }} />
              ) : (
                <div className="h-[220px] ">
                  {dialogueChartData.length > 0 ? (
                    <SmoothLineChart
                      height={210}
                      data={dialogueChartData}
                      isShowDialog={isShowDialog}
                    />
                  ) : (
                    <div className="h-full">
                      <NotData />
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      ) : (
        <div className=" mb-2  gap-4 ">
          <div
            className="hide-scrollbar w-full flex-1 overflow-auto rounded-default py-2 "
            style={{ backgroundColor: '#fff', position: 'relative', zIndex: 1 }}
          >
            <div className="px-4">
              <div className=" flex h-[40px] items-center text-xl font-semibold ">
                <div className="mr-2 h-3 w-3  rounded-full border-[3px] border-[#1B6DFA]" />
                用户趋势
              </div>
              <TipDesc
                title="展示平台用户数量随时间的变化趋势，帮助分析用户活跃度和增长情况"
                className="!my-0"
              />
              <div className=" gap-4">
                {userTrendsList.map((item: any, index: number) => {
                  return (
                    <div
                      key={index}
                      className="   mt-2 flex  h-[108px] w-full  rounded-md bg-[#F7F8FA] p-4 text-text-4"
                    >
                      <div className="mr-3 flex h-11 w-11 items-center justify-center rounded-md bg-white">
                        <SvgIcon
                          size={24}
                          icon={
                            item.key == 'total'
                              ? 'reportline1'
                              : item.key == 'new'
                              ? 'reportline2'
                              : 'reportline3'
                          }
                        />
                      </div>
                      <div>
                        <div className="flex items-center text-text-4">
                          {handleTrendsChange(item.key)}
                          <Tooltip title={tooltipMap[item.key]}>
                            <div className="flex">
                              <SvgIcon size={16} icon="report-is1" className="ml-1" />
                            </div>
                          </Tooltip>
                        </div>
                        <div className="mb-1">
                          <span className="mr-1 text-2xl font-extrabold text-text-5">
                            {userTrendsChartData.length > 0 ? item.count : '-'}
                          </span>
                          人
                        </div>
                        <div className="flex items-center">
                          {userTrendsChartData.length > 0 && (
                            <>
                              <span className=" text-sm text-text-4">
                                {activeRange === '7days'
                                  ? ' 周'
                                  : activeRange === '30days'
                                  ? '月'
                                  : ''}
                                环比
                                <span
                                  className={`${
                                    item.comparison == '-'
                                      ? 'text-text-4'
                                      : item.comparison == 0
                                      ? 'text-[#1E6FF8]'
                                      : item.comparison > 0
                                      ? 'text-[#0AA664]'
                                      : 'text-error'
                                  }
                                      px-1
                                      `}
                                >
                                  {item.comparison > 0 ? '+' : ''}
                                  {item.comparison == '-'
                                    ? '-'
                                    : (() => {
                                        const percent = (item.comparison * 100).toFixed(2);
                                        return percent.endsWith('.00')
                                          ? `${parseInt(percent, 10)}%`
                                          : `${percent}%`;
                                      })()}
                                </span>
                              </span>
                              {item.comparison !== 0 && item.comparison !== '-' ? (
                                <SvgIcon
                                  size={16}
                                  icon={item.comparison > 0 ? 'report-is-top ' : 'report-is-bottom'}
                                />
                              ) : (
                                <div className="text-[#1E6FF8]">-</div>
                              )}
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            <div className="mt-2">
              {statisticsLoading ? (
                <Skeleton active paragraph={{ rows: 5 }} style={{ padding: '10px' }} />
              ) : (
                <div className="h-[220px]">
                  {userTrendsChartData.length > 0 ? (
                    <UserBarChart data={userTrendsChartData} height={210} />
                  ) : (
                    <div className="h-full">
                      <NotData />
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
          <div className="hide-scrollbar w-full flex-1 overflow-auto rounded-default bg-white py-2 ">
            <div className="px-4">
              <div className="flex h-[40px] items-center justify-between">
                <div className="flex items-center text-xl font-semibold ">
                  <div className="mr-2 h-3 w-3  rounded-full border-[3px] border-[#1B6DFA]" />
                  <div className="flex cursor-pointer items-center">
                    <span className={` mr-4`}>{isShowDialog ? '对话趋势' : '性能趋势'}</span>
                  </div>
                </div>
                <div className="flex h-8 w-[168px] cursor-pointer items-center justify-center rounded-md border border-line-2 p-1 text-text-4 ">
                  <div
                    className={`${
                      isShowDialog ? 'rounded bg-fill-1 font-semibold text-[#1E6FFA]' : ' '
                    } w-1/2 text-center `}
                    onClick={() => {
                      setIsShowDialog(true);
                    }}
                  >
                    对话趋势
                  </div>
                  <div
                    className={`${
                      isShowDialog ? '' : 'rounded bg-fill-1 font-semibold text-[#1E6FFA]'
                    } w-1/2 text-center `}
                    onClick={() => {
                      setIsShowDialog(false);
                    }}
                  >
                    性能趋势
                  </div>
                </div>
              </div>
              <TipDesc
                title={
                  isShowDialog
                    ? '统计和展示用户与系统的对话数量及变化趋势'
                    : '展示系统首字时延的变化趋势，反映系统响应速度和性能表现'
                }
                className="!my-0"
              />
              <div className=" gap-4">
                {dialogueList.map((item: any, index: number) => {
                  return (
                    <div
                      key={index}
                      className={` flex h-[108px]  ${
                        isShowDialog ? 'w-full' : 'w-full'
                      } mt-2  rounded-md bg-[#F7F8FA]  p-4 text-text-4 `}
                    >
                      <div className="mr-3 flex h-11 w-11 items-center justify-center rounded-md bg-white">
                        <SvgIcon
                          size={24}
                          icon={
                            item.key == 'session'
                              ? 'reportline4'
                              : item.key == 'TTFB'
                              ? 'reportline6'
                              : 'reportline5'
                          }
                        />
                      </div>
                      <div>
                        <div className="flex items-center">
                          {handleTrendsChange(item.key)}
                          <Tooltip title={tooltipMap[item.key]}>
                            <div className="flex">
                              <SvgIcon size={16} icon="report-is1" className="ml-1" />
                            </div>
                          </Tooltip>
                        </div>
                        <div className="mb-1">
                          <span className="mr-1 text-2xl font-extrabold text-text-5">
                            {dialogueChartData.length > 0 ? item.count : '-'}
                          </span>
                          {item.key == 'session' ? '个' : item.key == 'TTFB' ? '秒' : '条'}
                        </div>
                        <div className="flex items-center">
                          {dialogueChartData.length > 0 && (
                            <>
                              <span className=" text-sm text-text-4">
                                {activeRange === '7days'
                                  ? ' 周'
                                  : activeRange === '30days'
                                  ? '月'
                                  : ''}
                                环比
                                <span
                                  className={`${
                                    item.comparison == '-'
                                      ? 'text-text-4'
                                      : item.comparison == 0
                                      ? 'text-[#1E6FF8]'
                                      : item.comparison > 0
                                      ? 'text-[#0AA664]'
                                      : 'text-error'
                                  }
                                  px-1
                                  `}
                                >
                                  {item.comparison > 0 ? '+' : ''}
                                  {item.comparison == '-'
                                    ? '-'
                                    : (() => {
                                        const percent = (item.comparison * 100).toFixed(2);
                                        return percent.endsWith('.00')
                                          ? `${parseInt(percent, 10)}%`
                                          : `${percent}%`;
                                      })()}
                                </span>
                              </span>
                              {item.comparison !== 0 && item.comparison !== '-' ? (
                                <SvgIcon
                                  size={16}
                                  icon={item.comparison > 0 ? 'report-is-top ' : 'report-is-bottom'}
                                />
                              ) : (
                                <div className="text-[#1E6FF8]">-</div>
                              )}
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            <div className="mt-2">
              {statisticsLoading ? (
                <Skeleton active paragraph={{ rows: 5 }} style={{ padding: '10px' }} />
              ) : (
                <div className="h-[220px] ">
                  {dialogueChartData.length > 0 ? (
                    <SmoothLineChart
                      height={210}
                      data={dialogueChartData}
                      isShowDialog={isShowDialog}
                    />
                  ) : (
                    <div className="h-full">
                      <NotData />
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
      <div
        className={`flex rounded-default  ${isPc ? null : 'mx-auto mb-4'}`}
        style={{ width: isPc ? '' : '90vw' }}
      >
        {userLoading ? (
          <Skeleton active paragraph={{ rows: 10 }} style={{ padding: '10px' }} />
        ) : (
          <div className={`   h-[38vh] ${isPc ? 'flex' : ''} w-full gap-4`}>
            {/* {isPc && ( */}
            <div className={`${isPc ? 'w-1/3 p-4' : 'w-full pb-4'} rounded-default bg-white `}>
              <div>
                <div className="flex items-center">
                  <SvgIcon color="#1B6DFA" icon="Ellipse" />
                  <div
                    style={{
                      color: '#1D2129',
                      fontSize: '20px',
                      fontWeight: 'bold',
                      marginLeft: '10px',
                    }}
                  >
                    Top 10 问题
                  </div>
                </div>
                <TipDesc
                  title="列出用户最常咨询的前十个问题，帮助识别用户关注的热点话题和需求"
                  className="!my-0"
                />
                {topQuestions && topQuestions.length > 0 && (
                  <div className="mt-4 flex">
                    <tr className="w-10 leading-[42px]">#</tr>
                    <div className="w-full leading-[42px]">问题</div>
                    {/* <tr className="w-20 leading-[42px]">提及数量</tr> */}
                  </div>
                )}
                {topQuestions && topQuestions.length > 0 ? (
                  <div className=" h-[240px] overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]">
                    {topQuestions.map((item, index) => (
                      <div
                        style={{
                          height: '50px',
                          display: 'flex',
                          alignItems: 'center',
                          width: '100%',
                          fontSize: '16px',
                          overflow: 'auto',
                          whiteSpace: 'nowrap',
                          textOverflow: 'ellipsis',
                        }}
                        key={index}
                      >
                        {index < 3 ? (
                          <div
                            style={{
                              marginRight: '10px',
                              flexShrink: '0',
                              fontWeight: 'bold',
                              color: index == 0 ? '#E24741' : '#ED7943',
                              width: '24px',
                              height: '24px',
                              display: 'flex',
                              justifyContent: 'center',
                              alignItems: 'center',
                              backgroundColor: index == 0 ? '#FFECE8' : '#FFF2E8',
                              borderRadius: '50%',
                            }}
                          >
                            0{index + 1}
                          </div>
                        ) : (
                          <div
                            style={{
                              marginRight: '10px',
                              flexShrink: '0',
                              fontWeight: 'bold',
                              width: '24px',
                              height: '24px',
                              display: 'flex',
                              justifyContent: 'center',
                              alignItems: 'center',
                              borderRadius: '50%',
                            }}
                          >
                            {index !== 9 ? `0${index + 1} ` : index + 1}
                          </div>
                        )}
                        <div
                          title={item.question}
                          style={{
                            width: '100%',
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis',
                          }}
                        >
                          {item.question}
                        </div>
                        <tr className="w-20  text-center " style={{ fontWeight: 'bold' }}>
                          {item.frequency}
                        </tr>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div
                    style={{
                      height: '260px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <NotData />
                  </div>
                )}
              </div>
            </div>
            {/* )} */}

            <div className="w-full">
              <UserTable
                users={users}
                userCount={userCount}
                selectedRole={selectedRole}
                dateRange={dateRange}
              />
            </div>
          </div>
        )}
      </div>
      {/* <div style={{ height: '1px' }}></div> */}
    </div>
  );
}

function Render({ renderTitle }: ReportProps) {
  return (
    <ReportContextProvider>
      <Report renderTitle={renderTitle} />
    </ReportContextProvider>
  );
}

export default Render;
